<?php
/**前台用户个人中心控制器
 * Created by PhpStorm.
 * User: zxj
 * Date: 17/5/2
 * Time: 上午10:52
 */

namespace App\Http\Controllers\Home;

use App\Models\Appointment;
use App\Models\Card;
use App\Models\Charge;
use App\Models\Member;
use App\Models\PayLog;
use App\Models\Setting;
use App\Models\User;
use App\Support\Wechat\Payment;
use App\Support\Wechat\Payment\Order as payOrder;
use App\Support\Wechat\Payment\Business;
use App\Support\Wechat\Payment\UnifiedOrder;
use App\Jobs\PayOrder as checkPayOrder;
use Omnipay\Omnipay;


class PayController extends BaseController
{

    public function __construct(
        Appointment $appointment,
        PayLog $payLog,
        Setting $setting,
        User $user,
        Charge $charge,
        Card $card,
        Member $member
    )
    {
        parent::__construct();
        $this->appointment = $appointment;
        $this->user = $user;
        $this->charge = $charge;
        $this->card = $card;
        $this->setting = $setting->getSetting('wechat');
        $this->union = $setting->getSetting('union');
        $this->paylog = $payLog;
        $this->member = $member;
    }

    public function getChangePayState()
    {
        $res = $this->appointment->getChangeState(request());
        return ajax_return($res);
    }

    public function getWxpay()
    {
        $apid = request('aid');
        $this->dispatch(new checkPayOrder($apid));
        $appointment = $this->appointment->getOne(['id' => $apid]);
        $where['doctor_id'] = $appointment['doctor_id'];
        $where['depart_id'] = $appointment['depart_id'];
        $where['mark_time'] = $appointment['mark_time'];
        $where['status'] = 1;
        $res = $this->appointment->getOne($where);
        if ($res) {
            return ajax_return(['state' => 0, 'msg' => "该科室医生在该时间段已被预约，请选择其他时间段"]);
        }
        $user = $this->user->getOne(['id' => $appointment['user_id']]);
        /**
         * 检测订单是否有效(超时)
         */
        $nowdate = time(); // 当前时间戳
        $setting = new Setting();
        $time = $setting->getSetting('system');
        $remaintimes = $nowdate - strtotime($appointment['created_at']);
        $allowTime = $time['end_pay_time'] * 60;
        // 判断是否在允许支付时间范围内
        if ($remaintimes > $allowTime) {
            // 超时处理
            $this->appointment->delOrder($appointment['id']);
            return ajax_return(['state' => 0, 'msg' => "该预约已超时，请重新预约"]);
        }
        /**
         * 第 1 步：定义商户
         */
        $business = new Business(
            $this->setting['app_id'],
            $this->setting['app_secret'],
            $this->setting['mch_id'],
            $this->setting['mch_key']
        );
        /**
         * 第 2 步：定义订单
         */
//        $url = 'http://yiyuanshibao.com/w/pay/notify';
//        $out_trade_no = md5(uniqid().microtime());
        $payOrder = new payOrder();

        $payOrder->body = '订单编号:' . $appointment['order_no'];
        $payOrder->out_trade_no = $appointment['order_no'];
        $payOrder->total_fee = $appointment['register_price'] * 100;    // 单位为 “分”, 字符串类型
//        $payOrder->total_fee = 1;    // 单位为 “分”, 字符串类型
        $payOrder->openid = $user['openid'];
        $payOrder->notify_url = url('notify/pay');

        /**
         * 第 3 步：统一下单
         */

        $unifiedOrder = new UnifiedOrder($business, $payOrder);
        /**
         * 第 4 步：生成支付配置文件
         */
        $payment = new Payment($unifiedOrder);

        $config = $payment->getConfig(false);

        return ajax_return(['state' => 1, 'msg' => "支付配置文件已生成", 'data' => array('free' => $payOrder->out_trade_no, 'payconfig' => $config)]);
    }

    public function getAppointment()
    {
        $appoint = $this->appointment->getAppPointmentById(request());
        return ajax_return($appoint);
    }

    public function getWxcharge()
    {
        $money = intval(request('money', 0));
        $num = $this->charge->getCount(['user_id' => request('mid'), 'status' => 1]);
        if (!$money) {
            $ajaxData['state'] = 0;
            $ajaxData['msg'] = '充值金额必须大于0';
            return ajax_return($ajaxData);
        }
        if (!$num) {
            $ajaxData['state'] = 0;
            $ajaxData['msg'] = '首次充值金额不能低于1000';
            return ajax_return($ajaxData);
        }
        $uid = request('mid');
        $user = $this->user->getUser($uid);
        $card = $this->card->getOne(['card_no' => request('card_no')]);
        $cardno = 0;
        //his锁卡
        if (!$card) {
            $member = $this->member->getOne(['id'=>request('m_id')]);
            if (!$member) {
                $ajaxData['state'] = 0;
                $ajaxData['msg'] = '非法操作！';
                return ajax_return($ajaxData);
            }
            if($money < 1000) {
                $ajaxData['state'] = 0;
                $ajaxData['msg'] = '该就诊人首次充值不能低于1000！';
                return ajax_return($ajaxData);
            }
            $param['sca01'] = $member['reffer_id'];
            $param['amounts'] = $money;
            $res = apiCurl('lockCardNo',$param);
            if (!$res['Result']) {
                $ajaxData['state'] = 0;
                $ajaxData['msg'] = '锁卡失败，请联系管理员！';
                return ajax_return($ajaxData);
            }
            $cardno = $res['Cardno'];
        }

        /**
         * 第 1 步：定义商户
         */
        $business = new Business(
            $this->setting['app_id'],
            $this->setting['app_secret'],
            $this->setting['mch_id'],
            $this->setting['mch_key']
        );
        /**
         * 第 2 步：定义订单
         */
//        $url = 'http://yiyuanshibao.com/w/pay/notify';
        $out_trade_no = createOrderNo();
        $payOrder = new payOrder();
        $payOrder->body = '充值订单编号:' . $out_trade_no;
        $payOrder->out_trade_no = $out_trade_no;
        $payOrder->total_fee = $money * 100;    // 单位为 “分”, 字符串类型
        $payOrder->openid = $user['openid'];
        $payOrder->notify_url = url('notify/charge');

        /**
         * 第 3 步：统一下单
         */

        $unifiedOrder = new UnifiedOrder($business, $payOrder);
        /**
         * 第 4 步：生成支付配置文件
         */
        $payment = new Payment($unifiedOrder);

        $data['user_id'] = $uid;
        $data['card_id'] = $card ? $card['id'] : 0;
        $data['charge_no'] = $out_trade_no;
        $data['money'] = $money;
        $data['member_id'] = request('m_id');
        $data['card_no'] = $card ? $cardno : 0;
        $data['created_at'] = date('Y-m-d H:i:s', time());
        $res = $this->charge->add($data);

        $ajaxData['state'] = $res ? 1 : 0;
        $ajaxData['payconfig'] = $payment->getConfig(false);
        $ajaxData['msg'] = $res ? '支付配置文件已生成' : '生成充值订单失败';
        return ajax_return($ajaxData);
    }

    public function getPayLogList()
    {
        $res = $this->paylog->getMyLogList(request());
        return ajax_return($res);
    }

    public function payByCard()
    {
        $apid = request('aid');
        $this->dispatch(new checkPayOrder($apid));
        $appointment = $this->appointment->getOne(['id' => $apid]);
        $where['doctor_id'] = $appointment['doctor_id'];
        $where['depart_id'] = $appointment['depart_id'];
        $where['mark_time'] = $appointment['mark_time'];
        $where['status'] = 1;
        $res = $this->appointment->getOne($where);
        if ($res) {
            return ajax_return(['state' => 0, 'msg' => "该科室医生在该时间段已被预约，请选择其他时间段"]);
        }
        $user = $this->user->getOne(['id' => $appointment['user_id']]);
        /**
         * 检测订单是否有效(超时)
         */
        $nowdate = time(); // 当前时间戳
        $setting = new Setting();
        $time = $setting->getSetting('system');
        $remaintimes = $nowdate - strtotime($appointment['created_at']);
        $allowTime = $time['end_pay_time'] * 60;
        // 判断是否在允许支付时间范围内
        if ($remaintimes > $allowTime) {
            // 超时处理
            $this->appointment->delOrder($appointment['id']);
            return ajax_return(['state' => 0, 'msg' => "该预约已超时，请重新预约"]);
        }
        $this->appointment->dealCardOrder($appointment);
    }

    // 发起银联支付
    public function getUnionPay()
    {
        $apid = request('aid');
        $this->dispatch(new checkPayOrder($apid));
        $appointment = $this->appointment->getOne(['id' => $apid]);
        $where['doctor_id'] = $appointment['doctor_id'];
        $where['depart_id'] = $appointment['depart_id'];
        $where['mark_time'] = $appointment['mark_time'];
        $where['status'] = 1;
        $res = $this->appointment->getOne($where);
        if ($res) {
            return ajax_return(['state' => 0, 'msg' => "该科室医生在该时间段已被预约，请选择其他时间段"]);
        }
        /**
         * 检测订单是否有效(超时)
         */
//        $nowdate = time(); // 当前时间戳
//        $setting = new Setting();
//        $time = $setting->getSetting('system');
//        $remaintimes = $nowdate - strtotime($appointment['created_at']);
//        $allowTime = $time['end_pay_time'] * 60;
//        // 判断是否在允许支付时间范围内
//        if ($remaintimes > $allowTime) {
//            // 超时处理
//            $this->appointment->delOrder($appointment['id']);
//            return ajax_return(['state' => 0, 'msg' => "该预约已超时，请重新预约"]);
//        }
        //组合订单信息
        $order['orderId'] = $appointment['order_no'];  // 订单号
        $order['txnTime'] = date('YmdHis');
        $order['orderDesc'] = '订单编号:' . $appointment['order_no']; //订单名称
        $order['txnAmt'] = $appointment['register_price'] * 100; //订单价格，单位是："分" 1x100

        //银联支付配置
        $gateway = Omnipay::create('UnionPay_Express'); //银联全产品网关（PC，APP，WAP支付）
        $gateway->setMerId($this->union['mer_id']);  //商户号
        $gateway->setCertPath(storage_path('unionpay/certs') . '/' . $this->union['cert_path']); // 商户私钥证书
        $gateway->setCertDir(storage_path('unionpay/certs'));  //测试环境银联公钥证书
        $gateway->setCertPassword($this->union['cert_password']);  // 密码
        $gateway->setNotifyUrl(url('notify/unionpay')); // 支付后同步通知页面地址
        $gateway->setReturnUrl('http://www.baidu.com'); // 支付后同步通知页面地址
//        获取支付链接
        $response = $gateway->purchase($order)->send();
        return $response->getRedirectHtml();
    }
}
